package cn.marknum.gateway.cas;

import cn.marknum.cas.client.session.AuthorizationMappingStorage;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.Assert;

import java.time.Duration;

/**
 * @author zhangzhao    2022-02-17 17:39
 */
public class RedisAuthorizationMappingStorage implements AuthorizationMappingStorage {

    private String prefix = "auth-mapping:";
    private StringRedisTemplate stringRedisTemplate;

    public RedisAuthorizationMappingStorage(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public String removeSessionByMappingId(String paramString) {
        String authorization = this.stringRedisTemplate.opsForValue().get(prefix + paramString);
        if (authorization != null) {
            this.stringRedisTemplate.delete(prefix + paramString);
            this.stringRedisTemplate.delete(prefix + authorization);
        }
        return authorization;
    }

    @Override
    public void removeBySessionById(String authorization) {
        String mappingId = this.stringRedisTemplate.opsForValue().get(prefix + authorization);
        if (mappingId != null) {
            this.stringRedisTemplate.delete(prefix + authorization);
            this.stringRedisTemplate.delete(prefix + mappingId);
        }
    }

    @Override
    public void addSessionById(String paramString, String authorization) {
        Assert.notNull(paramString, "MappingId can not be null");
        Assert.notNull(authorization, "Authorization can not be null");
        this.stringRedisTemplate.opsForValue().set(prefix + paramString, authorization);
        this.stringRedisTemplate.opsForValue().set(prefix + authorization, paramString);
        this.stringRedisTemplate.expire(prefix + paramString, Duration.ofHours(8));
        this.stringRedisTemplate.expire(prefix + authorization, Duration.ofHours(8));
    }

    @Override
    public void clearExpired() {

    }
}
